import subprocess
from datetime import datetime
import json

urllib = {
    'grid-72h' : 'https://devapi.qweather.com/v7/grid-weather/72h?',
    'grid-24h' : 'https://devapi.qweather.com/v7/grid-weather/24h?',
    'solar-72h' : 'https://api.qweather.com/v7/solar-radiation/72h?',
    'solar-24h' : 'https://api.qweather.com/v7/solar-radiation/24h?',
    'caiyun' : 'https://api.caiyunapp.com/v2.6/v3DKUMrPa0FNtne2/116.41,39.92/hourly?hourlysteps=24'
}
# key = '3ea598fc968c4aa9b1e7e9f293afaead'    # paid
key = '96ba1faae93c4a79bb76e4abbddefa33'    # free
location = '116.41,39.92'

def get_weather(option, dump=True, file_path=None):
    """use api to fetch weather data and return a dict

    Args:
        option (str): as urllib members
        dump (bool, optional): dump into json or not. Defaults to True.
        file_path (str, optional): json file name, None refer to option. Defaults to None.

    Returns:
        dict: json data
    """    
    if option == 'caiyun':
        if file_path == None:
            file_path = 'caiyun.json'
        curl_command = f"curl '{urllib['caiyun']}'"
    else: 
        if file_path == None:
            file_path = f'{option}.json'
        curl_command = f"curl -L -X GET --compressed '{urllib[option]}location={location}&key={key}'"
    output = subprocess.check_output(curl_command, shell=True)
    output = output.decode('utf-8')

    data = json.loads(output)

    if dump == True:
        with open(file_path, 'w') as file_ptr:
            json.dump(data, file_ptr, indent=4)
    return data

def get_weather_data_for_solar(source='net'):
    """fetch data required for solar panel power predict

    Args:
        source (str, optional): 'file' | 'net'. Defaults to 'net'.

    Returns:
        list: 1*24*5
    """    
    data_for_solar_panel = []
    if source == 'file':
        with open('solar-24h.json', 'r') as file_ptr:
            data_solar = json.load(file_ptr)
        with open('caiyun.json', 'r') as file_ptr:
            data_caiyun = json.load(file_ptr)
    elif source == 'net':
        data_solar = get_weather('solar-72h')
        if data_solar['code'] != '200':
            return 'solar data fetch fialed'
        data_caiyun = get_weather('caiyun')
        if data_solar['status'] != 'ok':
            return 'caiyun data fetch fialed'
    else:
        print(f'invalid option source={source}')
        return 'invalid source'
    data_solar = data_solar['radiation']
    for i in range(24):
        data_for_solar_panel.append([
            float(data_caiyun['result']['hourly']['temperature'][i]['value']),
            float(data_caiyun['result']['hourly']['humidity'][i]['value']),
            float(data_caiyun['result']['hourly']['precipitation'][i]['value']),
            float(data_solar[i]['net']),
            float(data_solar[i]['diffuse'])
        ])
    return data_for_solar_panel

def get_weather_date_for_consumption(source='net'):
    """fetch data required for power consumption predict

    Args:
        source (str, optional): 'file' | 'net'. Defaults to 'net'.

    Returns:
        list: 1*24*16
    """    
    data_for_consonption = []
    if source == 'file':
        with open('grid-24h.json', 'r') as file_ptr:
            data_grid = json.load(file_ptr)
        with open('caiyun.json', 'r') as file_ptr:
            data_caiyun = json.load(file_ptr)
    elif source == 'net':
        data_grid = get_weather('grid-24h')
        if data_grid['code'] != '200':
            return 'grid data fetch failed'
        data_caiyun = get_weather('caiyun')
        print(data_caiyun)
        if data_caiyun['status'] != 'ok':
            return 'caiyun data fetch fialed'
    else:
        print(f'invalid option source={source}')
        return 'invalid source'
    '''time, temperature, humidity, visibility, apparentTemperature,
    pressure, windSpeed, cloudCover, windBearing, precipIntensity,
    dewPoint, precipProbability, week, hour, month'''
    data_grid = data_grid['hourly']
    for i in range(24):
        targettime = datetime.strptime(data_caiyun['result']['hourly']['precipitation'][i]['datetime'], '%Y-%m-%dT%H:%M%z')
        data_for_consonption.append([
            targettime.timestamp(),     # %z is supported on this machine
            float(data_caiyun['result']['hourly']['temperature'][i]['value']),
            float(data_caiyun['result']['hourly']['humidity'][i]['value']),
            float(data_caiyun['result']['hourly']['visibility'][i]['value']),
            float(data_caiyun['result']['hourly']['apparent_temperature'][i]['value']),
            float(data_caiyun['result']['hourly']['pressure'][i]['value']),
            float(data_caiyun['result']['hourly']['wind'][i]['speed']),
            float(data_caiyun['result']['hourly']['cloudrate'][i]['value']),
            float(data_caiyun['result']['hourly']['wind'][i]['direction']),
            float(data_caiyun['result']['hourly']['precipitation'][i]['value']),
            float(data_grid[i]['dew']),
            float(data_caiyun['result']['hourly']['precipitation'][i]['probability']),
            targettime.weekday(),
            targettime.hour,
            targettime.month
        ])
    return data_for_consonption


def main():
    data = get_weather_date_for_consumption(source='file')
    print(data)

if __name__ == '__main__':
    main()